package com.chain.BrotherExchange.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.CoinTypeList;
import com.chain.BrotherExchange.event.AddAddressSuccessEvent;
import com.chain.BrotherExchange.ui.core.BaseActivity;
import com.chain.BrotherExchange.utils.ActivityBarHelper;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.viewmodel.ExtractCoinAddressViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;
import com.example.common.zxing.ui.CaptureActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.Objects;

import butterknife.Bind;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static com.example.common.zxing.ui.CaptureActivity.INTENT_EXTRA_KEY_QR_SCAN;

/**
 * 添加提币地址
 */
public class AddExtractAddressActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    @Bind(R.id.affirm_button) View mAffirmButton;
    @Bind(R.id.remark_edit) EditText mRemarkEditText;
    @Bind(R.id.add_address_layout) View mAddAddressLayout;
    @Bind(R.id.coin_type_text) TextView mCoinTypeTextView;
    @Bind(R.id.address_edit_text) EditText mAddressEditText;
    @Bind(R.id.select_coin_type_layout) View mSelectCoinTypeLayout;
    @Bind(R.id.add_address_rq_image) View mAddAddressRQImage;

    private ExtractCoinAddressViewModel mViewModel;
    private int coinId = -1;

    public static void launch(Context context) {
        context.startActivity(new Intent(context, AddExtractAddressActivity.class));
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_add_extract_address;
    }

    @Override
    protected void initActions() {
        ActivityBarHelper.init(this, R.string.title_extract_address);

        // 请求、逻辑操作
        mViewModel = ViewModelProviders.of(this).get(ExtractCoinAddressViewModel.class);

        //ViewUtils.notEditable(mAddressEditText);

        // 添加地址
        mAffirmButton.setOnClickListener(v -> addAddress());

        // 扫描二维码添加地址
        mAddAddressRQImage.setOnClickListener(v -> requestPermission());

        // 所有货币列表
        mSelectCoinTypeLayout.setOnClickListener(v ->
                SelectedListActivity.launch(this, C.VALUE_COIN_TYPE)
        );
    }

    private void addAddress() {
        String address = mAddressEditText.getText().toString();
        String remark = mRemarkEditText.getText().toString();
        mViewModel.addAddress(coinId, address, remark).observe(this, resource -> {
            if (resource.state == Resource.Status.LOADING) {
                Androids.showProgressMessage(this, R.string.adding_address);
            } else {
                Androids.dismissProgressMessage();
                Androids.makeText(resource.message);
                if (resource.state == Resource.Status.SUCCESS) {
                    EventBus.getDefault().post(new AddAddressSuccessEvent());
                    finish();
                }
            }
        });
    }

    private void requestPermission() {
        String[] permissions = new String[]{Manifest.permission.CAMERA};
        if (!EasyPermissions.hasPermissions(this, permissions)) {
            String rationale = getString(R.string.please_approve_camera_permissions);
            EasyPermissions.requestPermissions(this, rationale, 0, permissions);
        } else {
            CaptureActivity.launch(this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            CaptureActivity.launch(this);
        } else if (data != null && requestCode == C.REQ_REGION_COIN_TYPE) {
            CoinTypeList.DataBean.ListBean bean = (CoinTypeList.DataBean.ListBean) data
                    .getSerializableExtra(C.EXTRA_COIN_TYPE);
            mCoinTypeTextView.setText(bean.getMark());
            coinId = bean.getToken_id();
        } else if (resultCode == 0xA1 && data != null) {
            Bundle bundle = data.getExtras();
            String scanResult = Objects.requireNonNull(bundle).getString(INTENT_EXTRA_KEY_QR_SCAN);
            mAddressEditText.setText(scanResult);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        CaptureActivity.launch(this);
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle(R.string.auto_authorization_failure)
                    .setRationale(R.string.please_manually_select_approve_camera_permissions).build().show();
        } else {
            Androids.makeText(R.string.authorization_failure);
        }
    }
}
